package slice

import (
	"fmt"
	"ibdreader/mysql_def"
	"os"
)

/**
 * 注意Golang读取文件后会默认将其存储在无符号字节数组中：[]uint8
 * 后续在解析处理转换为有符号字节数组中：[]int8
 */

func decodeInt32(in Input) int64 {
	checkPositionIndexes(in.Position, in.Position+mysql_def.SIZE_OF_INT)
	return (int64(int8(in.Data[in.Position+3])) & 0xff) | (int64(int8(in.Data[in.Position+2]))&0xff)<<8 | (int64(int8(in.Data[in.Position+1]))&0xff)<<16 | (int64(int8(in.Data[in.Position]))&0xff)<<24
}

func decodeByte(in Input) byte {
	checkPositionIndexes(in.Position, in.Position+mysql_def.SIZE_OF_BYTE)
	return byte(int8(in.Data[in.Position]))
}

func decodeInt64(in Input) int64 {
	checkPositionIndexes(in.Position, in.Position+mysql_def.SIZE_OF_LONG)
	return (int64(int8(in.Data[in.Position+7])) & 0xff) | (int64(int8(in.Data[in.Position+6]))&0xff)<<8 | (int64(int8(in.Data[in.Position+5]))&0xff)<<16 | (int64(int8(in.Data[in.Position+4]))&0xff)<<24 | (int64(int8(in.Data[in.Position+3]))&0xff)<<32 | (int64(int8(in.Data[in.Position+2]))&0xff)<<40 | (int64(int8(in.Data[in.Position+1]))&0xff)<<48 | (int64(int8(in.Data[in.Position]))&0xff)<<56
}

func decodeInt16(in Input) int64 {
	checkPositionIndexes(in.Position, in.Position+mysql_def.SIZE_OF_SHORT)
	return int64(int8(in.Data[in.Position]))<<8 | int64(int8(in.Data[in.Position+1]))&255
}

func decode3BytesInt(in Input) int64 {
	checkPositionIndexes(in.Position, in.Position+mysql_def.SIZE_OF_MEDIUMINT)
	return (int64(int8(in.Data[in.Position+2])) & 0xff) | (int64(int8(in.Data[in.Position+1]))&0xff)<<8 | (int64(int8(in.Data[in.Position]))&0xff)<<16
}

func decode6BytesInt(in Input) int64 {
	checkPositionIndexes(in.Position, in.Position+6)
	return (int64(int8(in.Data[in.Position+5])) & 0xff) | (int64(int8(in.Data[in.Position+4]))&0xff)<<8 | (int64(int8(in.Data[in.Position+3]))&0xff)<<16 | (int64(int8(in.Data[in.Position+2]))&0xff)<<24 | (int64(int8(in.Data[in.Position+1]))&0xff)<<32 | (int64(int8(in.Data[in.Position]))&0xff)<<40
}

func checkPositionIndexes(start int64, end int64) {
	if start < 0 || end < start || end > mysql_def.UNIV_PAGE_SIZE {
		fmt.Scanf("IndexOutOfBoundsException start: %d, end: %d, size: %d", start, end, mysql_def.UNIV_PAGE_SIZE)
		os.Exit(0)
	}
}
